package com.one.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.one.bean.Product;
import com.one.config.OrderFlashSaleConfig;
import com.one.constant.RedisPrefixConstant;
import com.one.mapper.ProductMapper;
import com.one.service.OrderFlashSaleService;
import com.one.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create on 2022-01-16
 * <p>
 * Author: LiangWei
 * <p>
 * Description:
 **/
@Service
public class OrderFlashSaleServiceImpl implements OrderFlashSaleService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderFlashSaleConfig orderFlashSaleConfig;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void initProdStockToRedis(String prodId) {
        //查出数据库里该商品的库存数量
        Product pro = productMapper.selectOne(new QueryWrapper<Product>().eq("id",Integer.valueOf(prodId)));
        //将该商品的库存数量同步到redis中（redis数据库里的格式{prod-stock:商品ID,该商品的库存数量}）
        if(redisUtils.get(orderFlashSaleConfig.getProdStockPrefix()+":"+prodId)==null){
            //如果没有同步库存，就同步库存
            redisUtils.set(orderFlashSaleConfig.getProdStockPrefix()+":"+prodId,pro.getCount());
        }
    }

    @Override
    public boolean lockFlashSaleUserProd(String userId, String prodId) {
        return redisUtils.lock(orderFlashSaleConfig.getLockUserProdPrefix()+":"+userId+prodId,null,orderFlashSaleConfig.getLockUserProdTime());
    }

    @Override
    public boolean checkProdStockEnough(String prodId) {
        return Integer.valueOf(redisUtils.get(orderFlashSaleConfig.getProdStockPrefix()+":"+prodId).toString())>0;
    }

    @Override
    public boolean checkProdStockLocked(String prodId) {
        return redisUtils.lock(orderFlashSaleConfig.getLockProdStockPrefix()+":"+prodId,null,orderFlashSaleConfig.getLockProdStockTime());
    }

    @Override
    public void releaseProdStockLocked(String proId) {
        redisUtils.delLock(orderFlashSaleConfig.getLockProdStockPrefix()+":"+proId);
    }

    @Override
    public int getTradeOrderStateFromRedis(String key) {
        if(!redisUtils.hasKey(key)){
            //默认正在创建中
            redisUtils.set(key,0);
        }
        return (int)redisUtils.get(key);
    }

    @Override
    public void subProdStockCount(String prodId, Integer buyCount) {
        redisUtils.decr(orderFlashSaleConfig.getProdStockPrefix()+":"+prodId,buyCount);
    }
}
